import 'package:get/get.dart';

import '../../data/repositories/device_repository.dart';
import '../../data/models/device_model.dart';

/// 设备业务服务
/// 封装设备数据获取、控制等相关的核心业务逻辑
class DeviceBusiness {
  // 注入设备仓库
  final DeviceRepository _deviceRepository = Get.find<DeviceRepository>();

  /// 获取设备列表
  /// 
  /// [userId] (可选) 用于筛选特定用户的设备
  /// [page] 页码
  /// [limit] 每页数量
  /// [filters] (可选) 其他筛选条件
  Future<List<DeviceModel>> fetchDeviceList({
    String? userId,
    int page = 1,
    int limit = 20,
    Map<String, dynamic>? filters,
  }) async {
    try {
      // 可以在这里添加业务逻辑，例如根据用户角色决定是否需要 userId
      final devices = await _deviceRepository.getDeviceList(
        userId: userId,
        page: page,
        limit: limit,
        filters: filters,
      );
      return devices;
    } catch (e) {
      print('DeviceBusiness - Fetch device list failed: $e');
      return []; // 返回空列表或重新抛出业务异常
    }
  }

  /// 获取特定设备详情
  Future<DeviceModel?> fetchDeviceDetails(String deviceId) async {
    try {
      final device = await _deviceRepository.getDeviceById(deviceId);
      return device;
    } catch (e) {
      print('DeviceBusiness - Fetch device details failed: $e');
      return null;
    }
  }

  /// 控制设备
  /// 
  /// [deviceId] 设备ID
  /// [command] 控制命令 (例如: 'turn_on', 'set_temperature')
  /// [params] 命令参数 (例如: {'value': 25})
  Future<bool> controlDevice(
    String deviceId,
    String command,
    Map<String, dynamic>? params,
  ) async {
    // 可以在这里添加业务规则，例如：
    // - 检查用户是否有权限控制该设备
    // - 验证命令和参数是否有效
    
    try {
      final success = await _deviceRepository.sendDeviceCommand(
        deviceId,
        command,
        params,
      );
      
      if (success) {
        // 控制成功后的业务逻辑，例如记录操作日志
      }
      return success;
    } catch (e) {
      print('DeviceBusiness - Control device failed: $e');
      return false;
    }
  }

  /// 添加新设备
  Future<DeviceModel?> addNewDevice(Map<String, dynamic> deviceData) async {
    // 可以在此添加业务验证逻辑
    try {
      final newDevice = await _deviceRepository.addDevice(deviceData);
      return newDevice;
    } catch (e) {
      print('DeviceBusiness - Add device failed: $e');
      rethrow;
    }
  }

  /// 更新设备信息
  Future<DeviceModel?> updateDeviceInfo(String deviceId, Map<String, dynamic> updateData) async {
    if (updateData.isEmpty) {
      throw Exception('没有提供需要更新的设备信息');
    }
    try {
      final updatedDevice = await _deviceRepository.updateDevice(deviceId, updateData);
      return updatedDevice;
    } catch (e) {
      print('DeviceBusiness - Update device failed: $e');
      rethrow;
    }
  }

  /// 删除设备
  Future<bool> removeDevice(String deviceId) async {
    try {
      return await _deviceRepository.deleteDevice(deviceId);
    } catch (e) {
      print('DeviceBusiness - Delete device failed: $e');
      return false;
    }
  }

  // 可以在这里添加更多设备相关的业务逻辑，例如：
  // - 处理设备分组
  // - 获取设备历史数据
  // - 设备固件升级流程等
} 